package com.steve.xfood.service.impl;

import com.steve.xfood.dto.OrderDTO;
import com.steve.xfood.enums.ResultEnum;
import com.steve.xfood.exception.XFoodException;
import com.steve.xfood.service.BuyerService;
import com.steve.xfood.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author steve
 * @date 2020/5/11 13:36
 */
@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {
    @Autowired
    private OrderService orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
        OrderDTO orderDTO = checkOrderOpenid(openid, orderId);
        return orderDTO;
    }

    @Override
    public void orderCancel(String openid, String orderId) {
        OrderDTO orderDTO = checkOrderOpenid(openid, orderId);
        if (orderDTO == null) {
            log.info("【取消订单】 查不到订单 orderId={}", orderId);
            throw new XFoodException(ResultEnum.ORDER_NOT_EXIST);
        }
        orderService.cancel(orderDTO);
    }

    /**
     * 方法抽取
     * @param orderId
     * @param openid
     * @return
     */
    private OrderDTO checkOrderOpenid(String openid, String orderId) {
        OrderDTO orderDTO = orderService.findOrderById(orderId);
        if (orderDTO == null) {
            return null;
        }
        if (!orderDTO.getBuyerOpenid().equals(openid)) {
            //传递的openid和用户在数据库订单的openid不一致，判断订单是否为当前用户拥有(openid的安全性判断)
            log.info("【查询订单详情】 openid不一致 orderId={}, openid={}", orderId, orderDTO.getBuyerOpenid());
            throw new XFoodException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
